package de.pharmacontrol.utils;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import javax.persistence.EntityManager;

import de.pharmacontrol.pilot.entities.Line;
import de.pharmacontrol.pilot.entities.LogEntry;
import de.pharmacontrol.pilot.entities.LogEntry.Type;
import de.pharmacontrol.pilot.entities.User;

public class DbLogHandler extends Handler {

	private EntityManager em;

	private User user = null;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	private Line line = null;

	public Line getLine() {
		return line;
	}

	public void setLine(Line line) {
		this.line = line;
	}

	public DbLogHandler(EntityManager e) throws IOException, SecurityException {
		em = e;
		setLevel(Level.INFO);
	}
    
	public boolean isLoggable(LogRecord record) {
		if (em == null || !em.isOpen() || record == null) {
			return false;
		}
		return super.isLoggable(record);
	}

	@Override
	public void setFormatter(Formatter newFormatter) throws SecurityException {
		//not used
	}
	
	private Type getTypeForLevel(Level level){
		LogEntry.Type type;
		switch (level.intValue()){
		case 800:
			type = LogEntry.Type.INFO;
			break;
		case 900:
			type = LogEntry.Type.WARNING;
			break;
		case 1000:
			type = LogEntry.Type.ERROR;
			break;
		default:
			type = LogEntry.Type.DEBUG;
			break;
		}
		return type;
		
	}
	@Override
	public void publish(LogRecord record) {
		if (!isLoggable(record)) {
		    return;
		}
		LogEntry entry = new LogEntry();
		entry.setLine(line);
		entry.setUser(user);

		entry.setType(getTypeForLevel(record.getLevel()));
//		entry.setInt2(record.getThreadID());
//		entry.setLong1(record.getSequenceNumber());

		entry.setTime(new Timestamp(record.getMillis()));
		entry.setMessage(record.getMessage());
		
//		em.getTransaction().begin();
		em.persist(entry);
//		em.getTransaction().commit();
	}

	@Override
	public void flush() {
		//em.flush();

	}

	@Override
	public void close() throws SecurityException {
		//em.close();
	}

}
